package com.leenmvc.core.security.dao.core;

import com.leenmvc.core.base.BaseBusinessDao;
import com.leenmvc.core.cache.CacheFactory;
import com.leenmvc.core.dao.communal.Wrapper;
import com.leenmvc.core.dao.mysql.wrapper.QueryWrapper;
import com.leenmvc.core.enums.CacheType;
import com.leenmvc.core.security.entity.core.*;
import com.leenmvc.core.security.service.core.SysMenuService;
import com.leenmvc.core.utils.collection.TreeUtils;
import com.leenmvc.core.utils.http.HttpContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Repository
public class SysUserDao extends BaseBusinessDao<SysUser> {

    private final static Logger logger = LoggerFactory.getLogger(SysUserDao.class);

    @Autowired
    private SysUserTokenDao sysUserTokenDao;

    @Autowired
    private SysRoleUserDao sysRoleUserDao;

    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    @Autowired
    private SysRoleDao sysRoleDao;

    @Autowired
    private SysMenuDao sysMenuDao;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysLanguageDao sysLanguageDao;

    @Autowired
    private SysRolePermissionDao sysRolePermissionDao;

    @Autowired
    private SysPermissionDao sysPermissionDao;

    /**
     * 根据token获取用户信息
     *
     * @return
     */
    public SysUser getUserByToken(String token) {
        SysUserToken userToken = sysUserTokenDao.get("token", token);
        Long userId = userToken.getUserId();
        SysUser user = get(userId);
        user.setToken(userToken);
        return user;
    }

    /**
     * 获取用户角色信息
     *
     * @param userId
     * @return
     */
    public List<SysRole> getUserRoles(Long userId) {
        List<SysRoleUser> sysRoleUsers = sysRoleUserDao.getList("userId", userId);
        List<SysRole> results = new ArrayList();
        for (SysRoleUser sysRoleUser : sysRoleUsers) {
            SysRole sysRole = sysRoleDao.get("id", sysRoleUser.getRoleId());
            if (sysRole != null) {
                results.add(sysRole);
            }
        }
        return results;
    }


    /**
     * 根据用户的id获取该用户的所有权限标识
     *
     * @param id
     * @return
     */
    public Set<String> getUserPermissions(Long id) {
        // 获取到用户
         SysUser sysUser = get(id);
        List<String> permissionList = null;
         if (sysUser.getSuperAdmin() == 1){
             QueryWrapper wrapper = sysPermissionDao.getQueryWrapper().incField("identification");
             permissionList = sysPermissionDao.getOneFieldList(wrapper);
         }else {
             permissionList = listBySqlKey("getPermissionList", "roleId", sysUser.getRoleId());
         }
//        List<SysRoleUser> roleUser = sysRoleUserDao.getList("userId", id);
//        for (SysRoleUser ru : roleUser) {
//            QueryWrapper wrapper = getQueryWrapper(SysRolePermission.class);
//            wrapper.incField("permissionId").eq("roleId", ru.getRoleId());
//            List<Long> rolePermissions = sysRolePermissionDao.getOneFieldList(wrapper);
//            Wrapper id1 = getQueryWrapper(SysPermission.class);
//            id1.in("id", rolePermissions).incField("identification");
//            permissionList.addAll(sysPermissionDao.getOneFieldList(id1));
//        }
        return new HashSet<String>(permissionList);
    }

    /**
     * 根据用户的id获取该用户的所有权限标识
     *
     * @param id
     * @return
     */
    public Set<SysPermission> getUserPermissionList(Long id) {
        List<SysPermission> permissionList = new ArrayList<>();
        List<SysRoleUser> roleUser = sysRoleUserDao.getList("userId", id);
        for (SysRoleUser ru : roleUser) {
            QueryWrapper wrapper = getQueryWrapper(SysRolePermission.class);
                    wrapper.incField("permissionId").eq("roleId", ru.getRoleId());
            List<Long> rolePermissions = sysRolePermissionDao.getOneFieldList(wrapper);
            Wrapper id1 = getQueryWrapper(SysPermission.class);
            id1.in("id", rolePermissions);
            permissionList.addAll(sysPermissionDao.query(id1));
        }
        return new HashSet<SysPermission>(permissionList);
    }

    /**
     * 根据用户 Id 获取用户菜单
     *
     * @param userId
     * @return
     */
    public List<SysMenu> getUserMenu(Long userId) {
        List<SysMenu> menuList = CacheFactory.get(CacheType.USER_INFO, userId + ":userMenu");
        if (menuList != null) {
            return menuList;
        }
//        // 获取用户对应角色id
//        SysUser sysUser = get(userId);
//        Wrapper wrapper = null;
//
//        // 通过角色id获取对应菜单id
//        wrapper = sysRoleMenuDao.getQueryWrapper();
//        wrapper.incField("menuId");
//        wrapper.eq("roleId", sysUser.getRoleId());
//        List<Long> menuIds = sysRoleMenuDao.getOneFieldList(wrapper);
//        wrapper = sysMenuDao.getQueryWrapper();
//        wrapper.in("id", menuIds.toArray());
//        wrapper.uEq("type",1);
//        wrapper.orderBy("sort", "asc");
//        //仅查询可显示的菜单
//        wrapper.eq("isShow",1);
//        List<SysMenu> userMenu = sysMenuDao.query(wrapper);
//        Iterator<SysMenu> iterator = userMenu.iterator();
//        while (iterator.hasNext()){
//            SysMenu next = iterator.next();
//            SysMenu parentMenu = sysMenuDao.getParentMenu(next);
//            if(null != parentMenu && parentMenu.getIsShow() == 0){
//                iterator.remove();
//            }
//        }
//        for (SysMenu menu : userMenu) {
//            SysLanguage language = sysLanguageDao.get("tableName", "sys_menu", "tableId", menu.getId(), "language", HttpContextUtils.getLanguage());
//            if (language != null) menu.setName(language.getFieldValue());
//        }
        List<SysMenu> userMenu = sysMenuService.listBySqlKey("getUserMenu",  "language", HttpContextUtils.getLanguage(), "userId", userId);
        List<SysMenu> build = TreeUtils.build(userMenu);
        return build;
    }

}
